package com.guigu.qingcheng.controller;

import com.guigu.qingcheng.service.OrderServiceFeign;
import com.guigu.qingcheng.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@Controller
public class WxPayController {

    @Autowired
    private OrderServiceFeign orderServiceFeign;


    @GetMapping("/createNative")
    @ResponseBody
    public Map createNative(String orderId, HttpServletRequest request){
       String username= JwtUtils.getMemberIdByJwtToken(request);
        Map map = orderServiceFeign.createNative(orderId, username);
        return map;
    }

    @RequestMapping("/notify")
    @ResponseBody
    public void notifyLogic(HttpServletRequest request){
        try {

            InputStream inputStream = (InputStream)request.getInputStream();
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            while ((len=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
            outputStream.close();
            inputStream.close();
            String result=new String (outputStream.toByteArray(),"utf-8");
            orderServiceFeign.notifyLogic(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 跳转微信支付页面
     * @param ordersn
     * @param model
     * @return
     */
    @GetMapping("/weixinpay")
    public String weixinpay(String ordersn, Model model){
        model.addAttribute("ordersn",ordersn);

        return "/weixinpay";
    }

    /**
     * 支付失败页面
     * @return
     */
    @RequestMapping("/payfail")
    public String payfail(){
        return "payfail";
    }
    /**
     * 测试页面
     * @return
     */
    @RequestMapping("/paytest")
    public String paytest(){
        return "test";
    }

    /**
     * 支付成功跳转
     * @param ordersn
     * @param model
     * @return
     */
    @GetMapping("/paysuccess")
    public String paysuccess(String ordersn,String money, Model model){
        model.addAttribute("money",money);
        model.addAttribute("ordersn",ordersn);
        return "/paysuccess";
    }
}
